/**
 * *****************************************************************************
 * Code by: Hitler
 *
 * Class: File
 *
 * Chuc nang: doc va ghi trong file.
 *
 * Ngay tao: 25/08/2012
 *
 * Ngay sua doi: 04/10/2012
 *
 * Nguoi sua doi: Hitler
 *
 ****************************************************************************
 */
package BusinessLogic;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class FileProcess {

    private String urlFile;
    private String stringFlag;
    private String[] rString;
    private String[] wString;
    private int numRow;

    public FileProcess() {
        this.urlFile = null;
        this.stringFlag = null;
        this.numRow = 0;
        this.rString = null;
        this.wString = null;
    }

    public FileProcess(String urlFile, String stringFlag, int numRow, String[] wString) {
        this.urlFile = urlFile;
        this.stringFlag = stringFlag;
        this.numRow = numRow;
        this.rString = new String[numRow];
        this.wString = wString;
    }
    //ghi moi noi dung mot file bat dau tu dong dau tien

    public void WriteFile() {
        try {
            try {
                FileOutputStream f = new FileOutputStream(this.urlFile);
                PrintWriter output = new PrintWriter(f, true);
                //mo file config, ghi vao file
                for (int i = 0; i < wString.length; i++) {
                    output.println(wString[i]);//ghi dong thu i
                }
            }
            catch(Exception ex){}
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
    //doc file: tra ve mot mang chuoi gia tri chua thong tin thoa gia trị bat dau stringFlag voi so dong numRow

    public String[] OpenFile() {
        try {
            try{
                FileInputStream o = new FileInputStream(this.urlFile);
                Scanner input = new Scanner(o, "UTF-8");
                //doc tiep tin
                //trong khi còn dòng để đọc
                int i = 0;
                while (input.hasNextLine()) {
                    //Đọc 1 dòng
                    String line = input.nextLine();
                    while (this.stringFlag.equals(line)) {
                        if (this.numRow != 0) {
                            this.rString[i++] = input.nextLine();// gan dong hien tai vao mang thu i
                        } else {
                            break;
                        }
                        this.numRow--;
                    }
                }
            }
            catch(Exception ex){}
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            return this.rString;
        }
    }
}
